package utils

import (
	"errors"
	"fmt"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

// claims := jwt.RegisteredClaims{
// 	ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
// 	IssuedAt:  jwt.NewNumericDate(time.Now()),
// 	NotBefore: jwt.NewNumericDate(time.Now()),
// 	Issuer:    "test",
// 	Subject:   "somebody",
// 	ID:        "1",
// 	Audience:  []string{"somebody_else"},
// }

func GenerateJwtToken(key []byte, expireAt time.Time, username string) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"exp": jwt.NewNumericDate(expireAt),
		"username": username,
	})
	return token.SignedString(key)
}

func ValidateJwtToken(key []byte, tokenString string) error {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return key, nil
	})
	
	switch {
	case token.Valid:
		return nil
	case errors.Is(err, jwt.ErrTokenMalformed):
		return errors.New("that's not even a token")
	case errors.Is(err, jwt.ErrTokenSignatureInvalid):
		return errors.New("invalid signature")
	case errors.Is(err, jwt.ErrTokenExpired) || errors.Is(err, jwt.ErrTokenNotValidYet):
		return errors.New("timing is everything")
	default:
		return fmt.Errorf("couldn't handle this token: %v", err)
	}
}